/*
 * j4Win
 *  http://code.google.com/p/j4win/
 *
 * Copyright (C) 2006-2007 Felix Geyer, Moritz Laschinger
 *
 * This file is part of j4Win.
 *
 * j4Win is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 2 as published by the Free Software Foundation.
 *
 * j4Win is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package j4win;

import java.awt.EventQueue;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;

abstract public class Network extends Thread {
	protected Socket socket;
	protected InputStream in;
	protected OutputStream out;
	
	private NetworkListener listener;
	
	private boolean headerReceived = false;
	private int size;
	private boolean sizeReceived = false;
	private NetPacket inPacket;
	
	private ArrayBlockingQueue<NetPacket> inQueue =  new ArrayBlockingQueue<NetPacket>(100);
	private ArrayBlockingQueue<NetPacket> outQueue = new ArrayBlockingQueue<NetPacket>(100);
	
	public final static int VERSION = 1;
	
	public Network(NetworkListener listener) {
		this.listener = listener;
	}
	
	private Runnable received = new Runnable() {
		public void run() {
			NetPacket p = inQueue.poll();
			listener.packetReceived(p);
		}
	};
	
	@Override
	public void run() {
		while (!socket.isClosed()) {
			while (!outQueue.isEmpty()) {
				try {
					NetPacket p = outQueue.poll();
					if (p.getID()==NetPacket.ID.Close) {
						close();
						break;
					}
					out.write(p.stream());
					out.flush();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			try {
				read();
				sleep(100);
			}
			catch (EOFException e) {
			}
			catch (IOException e) {
				try {
					socket.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	private void read() throws IOException, InterruptedException {
		if (!headerReceived) {
			if (in.available()>=4) {
				byte[] h = new byte[4];
				in.read(h);
				inPacket = new NetPacket(NetPacket.byteArrayToInt(h));
				headerReceived = true;
			}
			else
				return;
		}
		
		if (!sizeReceived) {
			if (in.available()>=4) {
				byte[] s = new byte[4];
				in.read(s);
				size = NetPacket.byteArrayToInt(s);
				sizeReceived = true;
				if (size==0) {
					emitPacket();
					return;
				}
			}
			else
				return;
		}
		
		byte[] d = new byte[size];
		int l = in.read(d);
		inPacket.add(d);
		size -= l;
		
		if (size==0) {
			emitPacket();
		}
	}
	
	private void emitPacket() throws InterruptedException {
		NetPacket packet = inPacket;
		
		headerReceived = false;
		sizeReceived = false;
		inPacket = null;
		
		inQueue.put(packet);
		EventQueue.invokeLater(received);
	}
	
	public void send(NetPacket packet) {
		try {
			outQueue.put(packet);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void close() {
		try {
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
